//
//  MXAddPlanController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/4.
//

#import "MXAddPlanController.h"
#import "MXFoodPlanDateCell.h"
#import "BRPickerView.h"
#import "MXFoodCountCell.h"
@interface MXAddPlanController () <UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UICollectionView *listCV;
@property (nonatomic,assign) NSInteger selectIndx;
@property (nonatomic,strong) NSArray *dateArray;
@property (nonatomic,copy) NSString *timeStr;
@property (nonatomic,strong) UILabel *weightLab;
@property (nonatomic,strong) UICollectionView *foodCV;
@property (nonatomic,assign) NSInteger foodIndx;
@property (nonatomic,strong) UITableView *bgTable;
@end

@implementation MXAddPlanController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#78787a"];
    self.selectIndx = -1;
    self.foodIndx = -1;
    self.timeStr = @"00:00:00";
    self.dateArray = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    [self createUI];
}

- (void)createUI {
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, kStatusBarHeight, kScreenW, 52)];
    topView.backgroundColor = [UIColor whiteColor];
    [topView dc_cornerRadius:15 rectCorner:UIRectCornerTopLeft | UIRectCornerTopRight];
    [self.view addSubview:topView];
    
    MJWeakSelf
    UILabel *cancleLab = [[UILabel alloc] init];
    cancleLab.userInteractionEnabled = YES;
    cancleLab.text = @"取消";
    cancleLab.textColor = [UIColor colorWithHexString:@"#000000"];
    cancleLab.font = PFRFont(16);
    [cancleLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tapCancle];
    }]];
    [topView addSubview:cancleLab];
    [cancleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.offset(21);
    }];
    
    UILabel *saveLab = [[UILabel alloc] init];
    saveLab.userInteractionEnabled = YES;
    saveLab.text = @"保存";
    saveLab.textColor = [UIColor colorWithHexString:@"#000000"];
    saveLab.font = PFRFont(16);
    [saveLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf tapSave];
    }]];
    [topView addSubview:saveLab];
    [saveLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-28);
        make.top.offset(21);
    }];
    
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = @"添加计划";
    [topView addSubview:titleLab];
    titleLab.textColor = [UIColor colorWithHexString:@"#000000"];
    titleLab.font =  PFRFontMedium(17);
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.centerX.mas_equalTo(topView);
    }];

    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(topView.frame), kScreenW, kScreenH-52-kStatusBarHeight)];
    bgView.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
    [self.view addSubview:bgView];
//    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.bottom.offset(0);
//        make.top.mas_equalTo(topView.mas_bottom);
//    }];
    
    UILabel *planLab = [[UILabel alloc] initWithFrame:CGRectMake(28, 10, 200, 14)];
    planLab.text = @"喂食计划";
    planLab.textColor = [UIColor colorWithHexString:@"#000000"];
    planLab.font = PFRFontMedium(13);
    [bgView addSubview:planLab];

    [bgView addSubview:self.listCV];
    self.listCV.frame = CGRectMake(25, CGRectGetMaxY(planLab.frame)+10, kScreenW-50, 58);
//    [self.listCV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(25);
//        make.right.offset(-25);
//        make.top.mas_equalTo(planLab.mas_bottom).offset(13);
//        make.height.mas_equalTo(58);
//    }];
    
    UILabel *timeLab = [[UILabel alloc] initWithFrame:CGRectMake(28, CGRectGetMaxY(self.listCV.frame)+10, 200, 14)];
    timeLab.text = @"设置时间";
    timeLab.textColor = [UIColor colorWithHexString:@"#000000"];
    timeLab.font = PFRFontMedium(13);
    [bgView addSubview:timeLab];
//    [timeLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(28);
//        make.top.mas_equalTo(self.listCV.mas_bottom).offset(18);
//    }];
    
    UIView *timeBg = [[UIView alloc] initWithFrame:CGRectMake(21, CGRectGetMaxY(timeLab.frame)+10, kScreenW-21, 200)];
    timeBg.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:timeBg];
    timeBg.layer.cornerRadius = 8;
    timeBg.layer.masksToBounds = YES;
//    [timeBg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(21);
//        make.right.offset(-21);
//        make.height.mas_equalTo(200);
//        make.top.mas_equalTo(timeLab.mas_bottom).offset(9);
//    }];
    
    BRDatePickerView *pick = [[BRDatePickerView alloc] initWithPickerMode:BRDatePickerModeHM];
    pick.isAutoSelect = YES;
    pick.numberFullName = YES;
    pick.showUnitType = BRShowUnitTypeNone;
    BRPickerStyle *style = [[BRPickerStyle alloc] init];
    style.separatorColor = [UIColor clearColor];
    style.selectRowColor = [UIColor colorWithHexString:@"#F4F4F4"];
    pick.pickerStyle = style;
    [pick addPickerToView:timeBg];
    [pick mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.top.offset(17);
        make.bottom.offset(-17);
        make.right.offset(-7);
    }];
    pick.resultBlock = ^(NSDate * _Nullable selectDate, NSString * _Nullable selectValue) {
        weakSelf.timeStr = selectValue;
    };
    
    
    UILabel *foodLab = [[UILabel alloc] initWithFrame:CGRectMake(28, CGRectGetMaxY(timeBg.frame)+10, 200, 14)];
    foodLab.text = @"设置出粮量";
    foodLab.textColor = [UIColor colorWithHexString:@"#000000"];
    foodLab.font = PFRFontMedium(13);
    [bgView addSubview:foodLab];
//    [foodLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(28);
//        make.top.mas_equalTo(timeBg.mas_bottom).offset(28);
//    }];
    
    UIView *foodBg = [[UIView alloc] initWithFrame:CGRectMake(21, CGRectGetMaxY(foodLab.frame)+10, kScreenW-21, 200)];
    foodBg.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:foodBg];
    foodBg.layer.cornerRadius = 8;
    foodBg.layer.masksToBounds = YES;

    
    self.weightLab = [[UILabel alloc] init];
    self.weightLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.5];
    self.weightLab.font = PFRFontSemibold(20);
    self.weightLab.text = @"0g";
    [foodBg addSubview:self.weightLab];
    [self.weightLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(30);
        make.centerX.mas_equalTo(foodBg);
    }];
    
    UILabel *noticeLab = [[UILabel alloc] init];
    noticeLab.text = @"实际结果与主粮颗粒大小及密度相关";
    noticeLab.font = PFRFontMedium(10);
    noticeLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.5];
    [foodBg addSubview:noticeLab];
    [noticeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(foodBg);
        make.top.mas_equalTo(self.weightLab.mas_bottom).offset(6);
    }];
    
    [foodBg addSubview:self.foodCV];
    [self.foodCV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(-37);
        make.height.mas_equalTo((kScreenW -42) / 5.0);
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.contentView.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
    return cell;
    return [[UITableViewCell alloc] init];
}



- (UICollectionView *)listCV {
   if (!_listCV) {
       UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
       layout.itemSize = CGSizeMake((kScreenW - 50-42) / 7.0, 58);
       layout.minimumLineSpacing = 7;
       layout.minimumInteritemSpacing = 7;
       layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
       _listCV = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
       _listCV.backgroundColor = [UIColor clearColor];
       _listCV.delegate = self;
       _listCV.dataSource = self;
       _listCV.showsVerticalScrollIndicator = NO;
       _listCV.showsHorizontalScrollIndicator = NO;
       [_listCV registerClass:[MXFoodPlanDateCell class] forCellWithReuseIdentifier:@"MXFoodPlanDateCell"];
       
       }
    return _listCV;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.foodCV) {
        return 5;
    }
    return 7;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    if (collectionView == self.foodCV) {
        MXFoodCountCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MXFoodCountCell" forIndexPath:indexPath];
        [cell reloadCellWithSelect:indexPath.item == self.foodIndx count:[NSString stringWithFormat:@"%ld",indexPath.item+1]];
        return cell;
    }
    
    MXFoodPlanDateCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MXFoodPlanDateCell" forIndexPath:indexPath];
    [cell reloadCellWithSelect:(self.selectIndx == indexPath.item) title:self.dateArray[indexPath.item]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (collectionView == self.foodCV) {
        self.foodIndx = indexPath.item;
        [self.foodCV reloadData];
        self.weightLab.text = [NSString stringWithFormat:@"%ldg",(long)((indexPath.item + 1) *10)];
    } else {
        self.selectIndx = indexPath.item;
        [self.listCV reloadData];
    }
}


- (UICollectionView *)foodCV {
   if (!_foodCV) {
       UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
       layout.itemSize = CGSizeMake((kScreenW -42) / 5.0, (kScreenW -42) / 5.0);
       layout.minimumLineSpacing = 0;
       layout.minimumInteritemSpacing = 0;
       layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
       _foodCV = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
       _foodCV.backgroundColor = [UIColor clearColor];
       _foodCV.delegate = self;
       _foodCV.dataSource = self;
       _foodCV.showsVerticalScrollIndicator = NO;
       _foodCV.showsHorizontalScrollIndicator = NO;
       [_foodCV registerClass:[MXFoodCountCell class] forCellWithReuseIdentifier:@"MXFoodCountCell"];
       
       }
    return _foodCV;
}

- (void)tapCancle {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)tapSave {
    if (self.selectIndx == -1) {
        [self.view xjmakeToast:@"请选择星期"];
        return;
    }
    if (self.foodIndx == -1) {
        [self.view xjmakeToast:@"请设置出粮量"];
        return;
    }
    NSString * grainOuput = [NSString stringWithFormat:@"%ld",(self.foodIndx + 1)];
    
    NSString *planDate = @"";
    if (self.selectIndx == 0) {
        planDate = @"7";
    } else {
        planDate = [NSString stringWithFormat:@"%ld",self.selectIndx];
    }
    NSString *timeStr = [self.timeStr stringByAppendingString:@":00"];
    NSDictionary *param = @{@"deviceId":SAFEPARAMETER(self.model.ID),
                            @"grainOuput":grainOuput,
                            @"planDate":planDate,
                            @"planName":@"喂食计划",
                            @"planTimeStr":timeStr
                            };
    MJWeakSelf
    [self.view makeToastActivity];
//    NSString *urlStr = [NSString stringWithFormat:@"%@?deviceId=%@&grainOuput=%@&planDate=%@&planName=%@&planTimeStr=%@",@"api/app/appFeedingPlan/add",SAFEPARAMETER(self.model.ID),grainOuput,planDate,@"周一上午10点喂食",timeStr];
    [[DCHttpClient shareClient] requestWithPath:@"api/app/appFeedingPlan/add" params:param httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.view xjmakeToast:@"添加成功"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"addfoodplansuccess" object:nil];
            [weakSelf performSelector:@selector(addFoodSuccess) afterDelay:1.5];
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
    }];
}

- (void)addFoodSuccess {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
